//客户端代码打包 production
const path = require('path');
const webpack = require('webpack');
const webpackMerge = require('webpack-merge');
const baseConfig = require('./webpack.base');
const LessPluginFunctions = require('less-plugin-functions');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const TerserWebpackPlugin = require('terser-webpack-plugin');
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin');
const WorkboxPlugin = require('workbox-webpack-plugin')
const os = require('os');
//预渲染
// const PreRender = require('prerender-spa-plugin');

const config = webpackMerge(baseConfig, {
  mode: 'production',
  output: {
    publicPath: './',
    path: path.join(__dirname, '../dist'),
    // libraryTarget: 'var',
    // library: '_dll_vendors',
    filename: '[name].js',
  },
  entry: {
    // client: [path.resolve(__dirname, '../src/index.tsx')],
    client: [path.resolve(__dirname, '../src/index.tsx')]
  },
  devtool: 'cheap-module-eval-source-map',
  module: {
    rules: [
      {
        test:/\.(js|jsx|ts|tsx)$/,
        exclude: /(node_modules|bower_components)/,
        use: 'happypack/loader?id=babel'
      },
      {
        test: /\.css$/,
        use: [
          MiniCssExtractPlugin.loader,
          {
            loader: 'css-loader',
            options: {
              // importLoaders: 1,
              sourceMap: true,
              // modules: true
            }
          },
          // {
          //   loader: 'postcss-loader'
          // }
        ]
      },
      {
        test: /\.(scss|sass)$/,
        use: [
          MiniCssExtractPlugin.loader,
          {
            loader: 'css-loader',
            options: {
              // importLoaders: 1,
              sourceMap: true,
              modules: {
                localIdentName: '[local]-[hash:base64:5]',
              }
            }
          },
          {
            loader: 'postcss-loader'
          },
          {
            loader: 'sass-loader',
            options: {
              sourceMap: true
            }
          }
        ]
      },
      {
        test: /\.less$/,
        use: [
          MiniCssExtractPlugin.loader,
          {
            loader: 'css-loader',
            options: {
              // importLoaders: 1,
              sourceMap: true,
              modules: {
                localIdentName: '[local]-[hash:base64:5]',
              }
            }
          },
          {
            loader: 'postcss-loader'
          },
          {
            loader: 'less-loader',
            options: {
              plugins: [
                new LessPluginFunctions()
              ],
              sourceMap: true,
            }
          }
        ]
      }
    ]
  },
  optimization: {
    // minimizer: [
      usedExports: true,
      minimize: true,
      concatenateModules:true,
    //   // new UglifyJsPlugin(),
    //   new OptimizeCSSAssetsPlugin(),
    // ],
    splitChunks: {
      chunks:"all",
      minSize: 30000,
      maxSize: 0,
      minChunks: 1,
      maxAsyncRequests: 6, // 每个异步加载模块最多能被拆分的数量
      maxInitialRequests: 6, // 每个入口和它的同步依赖最多能被拆分的数量
      enforceSizeThreshold: 50000, // 强制执行拆分的体积阈值并忽略其他限制
      automaticNameDelimiter: '~',
      name: true,
      cacheGroups: {
        vendors: {
          chunks:'all',
          name: `vendors`,
          test: /(react|react-dom|react-dom-router|babel-polyfill)/,
          priority: 20,
        },
        "antd-vendor": {
          test: /antd/,
          name: 'antd-vendor',
          priority:20,
          reuseExistingChunk: false,
        },
        "echartsVendor": {
          test: /(echarts|zrender)/,
          priority: 20,
          name: 'echarts-vendor',
        },
        'async-commons': { // 其余异步加载包
          chunks: 'async',
          minChunks: 2,
          name: 'async-commons',
          priority: 10,
        },
        commons: {
          chunks: 'all',
          minChunks:2,
          name:`commons`,
          priority: 0,
        }
        // vendors: {
        //   name: `chunk-vendors`,
        //   test: /[\\/]node_modules[\\/]/,
        //   priority: -10,
        // },
        // default: { //默认打包模块
        //   priority: -20,
        //   reuseExistingChunk: true, //模块嵌套引入时，判断是否复用已经被打包的模块
        //   filename: 'common.js'
        // }
      }
      // cacheGroups: {
      //   vendor: {
      //     test: /\.js$/,
      //     chunks: 'all', //表示显示块的范围，有三个可选值：initial(初始块)、async(按需加载块)、all(全部块)，默认为all;
      //     enforce: true
      //   },
      // }
    }
  },
  plugins: [
    new webpack.NoEmitOnErrorsPlugin(),
    new HtmlWebpackPlugin({
      template: './src/index.html',
      inject: true,
      // favicon: './client/static/image/logo.jpg',
      filename: 'index.html',
      hash: true,
      chunks: ['vendors','commons','client','antd-vendor','echarts-vendor']
      // loading: loading
    }),
    new webpack.DllReferencePlugin({
        context: __dirname,
        manifest: require('./dll/vendors.manifest.json')
    }),
    new AddAssetHtmlPlugin([
        {
            // 要添加到编译中的文件的绝对路径，以及生成的HTML文件。支持 globby 字符串
            filepath: require.resolve('./dll/vendors.dll'),
            // 文件输出目录
            outputPath: './dist',
            // 脚本或链接标记的公共路径
            publicPath: './dist'
        }
    ]),
    new webpack.HotModuleReplacementPlugin(), //热模块替换HMR
    new MiniCssExtractPlugin({ // 在plugins中配置属性
      filename: 'css/[name]-[contentHash].css', // 配置提取出来的css名称
      chunkFilename: 'css/chunk-[id].css'
    }),
    new BundleAnalyzerPlugin(),
    new WorkboxPlugin.GenerateSW({
      clientsClaim: true,
      skipWaiting: true
    })
    // new CompressionWebpackPlugin({
    //   filename: '[path].gz[query]',
    //   algorithm: 'gzip',
    //   test: /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i,
    //   threshold: 10240,
    //   minRatio: 0.8,
    //   deleteOriginalAssets: true
    // })
  ]
});

module.exports = config;
